"""This module is used to fetch any kind of system information or statistics
"""

import re
import subprocess
import ma.const


def cpu_mpstats():
    """Get CPU stats. Get two usage percentages: the first one of user
    and the second one of the system cpu usage percentage. REQUIRES mpstat
    to be installed on the machine
    """
    
    # run the mpstat program
    proc = subprocess.Popen('mpstat', shell=True, stdout=subprocess.PIPE)
    # get the stdout
    proc_out = proc.communicate()[0]
    # forward the message to the intr string
    proc_out = proc_out[proc_out.find('intr/s'):]
    # get all cpu times
    cpu_times = re.findall(r'(\d+.\d+)\s+(\d+.\d+)\s+(\d+.\d+)\s+(\d+.\d+)\s+(\d+.\d+)\s+(\d+.\d+)\s+(\d+.\d+)\s+(\d+.\d+)', proc_out)
    cpu_times = cpu_times[0]
    return cpu_times[0], cpu_times[2] 


def cpu_topstats():
    """Get CPU stats. Get two usage percentages: the first one of user
    and the second one of the system cpu usage percentage. REQUIRES top
    to be installed on the machine
    """
    
    # run the top program in batch mode for 1 iteration
    proc = subprocess.Popen('top -b -n 1', shell=True, stdout=subprocess.PIPE)
    # get the stdout
    proc_out = proc.communicate()[0]
    # forward the message to the Cpu(s) string, and chop the text
    proc_out = proc_out[proc_out.find('Cpu(s):'):]
    proc_out = proc_out[:80]
    # get all cpu times
    cpu_times = re.findall(r'(\d+.\d+)%\s*us,\s+(\d+.\d+)%\s*sy', proc_out)
    cpu_times = cpu_times[0]
    return cpu_times[0], cpu_times[1]
  
    
def net_stats(already_received=0, already_sent=0):
    """Get the current interfaces tx, rx number of KB transferred since last
    function call. The first value is of KB rx, and the second value is of KB
    of tx. If already_received and/or already_sent is provided, it is minused
    from the values that were going to be returned
    """
    
    # get the communication network interface
    net_int = ma.const.XmlData.get_str_data(ma.const.xml_network_interface)
    # run the ifconfig command to get network values
    proc = subprocess.Popen('ifconfig ' + net_int, shell=True, stdout=subprocess.PIPE)
    # get the stdout
    proc_out = proc.communicate()[0]
    # forward the message to the interface string
    proc_out = proc_out[proc_out.find('RX bytes:'):]
    # get interface rx, tx values
    net_stats = re.findall(r'RX bytes:(\d+).+TX bytes:(\d+)', proc_out)
    # get total bytes received and transferred
    rx = int(net_stats[0][0])
    tx = int(net_stats[0][1])
    recvd = rx - already_received
    sent = tx - already_sent
    return recvd, sent
